package yeepay

import (
	"context"
	"errors"
	"github.com/shopspring/decimal"
	"github.com/yop-platform/yop-go-sdk/yop/client"
	"github.com/yop-platform/yop-go-sdk/yop/constants"
	"github.com/yop-platform/yop-go-sdk/yop/request"
	model2 "simplifly-tech/payment/model"
	"strconv"
)

func (yeePayService *YeePayService) Refund(ctx context.Context, refundData *model2.RefundData) (string, error) {
	refundRequestId, err := yeePayService.createRefund(
		refundData.ParentOrderId+"-"+strconv.Itoa(int(refundData.ParentIncomeID)),
		refundData.OrderID+"-"+strconv.Itoa(int(refundData.ParentIncomeID)),
		refundData.ReferenceID,
		refundData.NotifyUrl,
		refundData.Amount,
	)

	return refundRequestId, err
}

func (yeePayService *YeePayService) createRefund(orderId, refundRequestId, uniqueOrderNo string, notifyUrl string, refundAmount decimal.Decimal) (result string, err error) {

	var priKey = request.IsvPriKey{Value: yeePayService.MchPrivateKey, CertType: request.RSA2048}
	var yopRequest = request.NewYopRequest(constants.POST_HTTP_METHOD, "/rest/v1.0/trade/refund")

	yopRequest.AppId = yeePayService.AppKey
	yopRequest.IsvPriKey = priKey
	yopRequest.AddParam("parentMerchantNo", yeePayService.ParentMerchantNo) //发起方商编
	yopRequest.AddParam("merchantNo", yeePayService.ParentMerchantNo)       //商户编号
	yopRequest.AddParam("orderId", orderId)                                 //订单编号
	yopRequest.AddParam("refundRequestId", refundRequestId)                 //商户收款请求号
	yopRequest.AddParam("refundAmount", refundAmount.InexactFloat64())      //退款金额
	yopRequest.AddParam("uniqueOrderNo", uniqueOrderNo)                     //易宝订单号
	// TODO 设置回调地址 【已处理】  暂时没有处理
	//yopRequest.AddParam("notifyUrl", config.SecureUrl("/notify/yeepay/flight/order/refund"))
	yopRequest.AddParam("notifyUrl", notifyUrl)

	yopResp, err := client.DefaultClient.Request(yopRequest)
	if nil != err {
		return
	}

	Result := yopResp.Result.(map[string]interface{})
	if Result["code"] != "OPR00000" {
		err = errors.New(Result["message"].(string))
		return
	}
	return Result["refundRequestId"].(string), nil
}
